package com.runmi.webchat.aftersale.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.runmi.webchat.aftersale.common.result.Result;
import com.runmi.webchat.aftersale.common.result.ResultFactory;
import com.runmi.webchat.aftersale.common.utils.DESUtil;
import com.runmi.webchat.aftersale.common.utils.StringUtil;
import com.runmi.webchat.aftersale.util.Constants;


public class AuthInterceptor extends HandlerInterceptorAdapter {

	protected static final Log log = LogFactory.getLog("logFile");
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//允许跨域
//		response.setHeader("Access-Control-Allow-Origin", "*");
//		response.setHeader("Access-Control-Allow-Credentials", "true");
//		response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
//		response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me, jsessionid");

		// 请求的uri
		String uri = request.getRequestURI();
		// 请求方式
		String method = request.getMethod();
		//http://127.0.0.1:7005/assest/i/bg-2.jpg
	
		log.info("uri = " + uri + ", method = " + method );

		// 登录、登出、注册、验证码不拦截
		if (!uri.endsWith("login") && !uri.endsWith("reg") && !uri.endsWith("logout") && !uri.contains("/print/datasource") 
				&& !"OPTIONS".equals(method)
				&& !uri.contains("css")
				&& !uri.contains("error")
				&& !uri.contains("file/upload")
				&& !uri.contains("images")
				&& !uri.equals("/")
				&& !uri.contains("api-docs")
				&& !uri.contains("/contains")
				&& !uri.equals("/scmapi/")
				&& !uri.contains("/webchatapi/")
				&& !uri.contains("swagger")
				&& !uri.contains("export")
				&& !uri.contains("js")
				) {
			// 校验登录
			String tocken=getTocken(request,response);
			if (StringUtil.isBlank(tocken)) {
				response.setStatus(200);
				String port=request.getServerPort()==80?"":":" + request.getServerPort();
				String url=request.getScheme()  + "://" + request.getServerName() + port +  "" + request.getContextPath() + "/login";
				response.sendRedirect(url);
				return false;
//				response.setCharacterEncoding("UTF-8");  
//				 response.setContentType("application/json; charset=utf-8");  
//				 PrintWriter out = null;  
//				     try {  
//				    	 Result result=  ResultFactory.getResultFailNotLogin();
//				         out = response.getWriter();  
//				         out.append(result.toString());  
//				         //logger.debug("返回是\n");  
//				         //logger.debug(responseJSONObject.toString());  
//				     } catch (IOException e) {  
//				         e.printStackTrace();  
//				     } finally {  
//				         if (out != null) {  
//				             out.close();  
//				         }  
//				    }  
//
//				return false;
			}

			/*// 权限控制
			if (!AccountUtil.hasAuthority(sessionid, uri)) {
				return false;
			}*/
		}
		
		response.setStatus(200);
		return true;
	}
	protected String getTocken(HttpServletRequest request,HttpServletResponse response){
		String result=null;
		try{
			//String tocken=request.getHeader("tocken"); //
			String tocken=this.readCookie(request, Constants.SYSTEM_COOKIE);
			if(StringUtil.isNotEmptyStr(tocken)){
				tocken = URLDecoder.decode(tocken, "UTF-8");
				tocken=DESUtil.decryptDES(tocken);
				this.log.info(tocken);
				String[] tockens=tocken.split("-");
				String system=tockens[0];
				if(!system.equals("scm")){
					tocken="";
				}
			}
			return tocken;
			//String tocken=shopId + "-"  + userId  + "-"+ DateUtil.getToday("yyyyMMddHHmmss");
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return result;
	}
	

	private String readCookie(HttpServletRequest request,String name) throws ServletException, IOException {
		String value = null;
		if (name != null) {
			Cookie cookies[] = request.getCookies();
			if (cookies != null && cookies.length >= 0) {
				for (int i = 0; i < cookies.length; i++) {
					Cookie cookie = cookies[i];
					if (name.equals(cookie.getName())) {
						value = cookie.getValue();
					}
				}
			}
		}
		return value;
	}
}
